import copy
import logging
from datetime import datetime

from flask import jsonify

from airflow.patsnap.service import user_service
from airflow.models import User, DagPickle
from airflow.models.idata_auth_resource import AuthResource
from airflow.models.idata_auth_role import AuthRole
from airflow.models.idata_project import Project
from airflow.models.idata_project_datasource import ProjectDatasource
from airflow.models.idata_project_user import ProjectUser
from airflow.models.idata_task import Task
from airflow.models.idata_workflow import WorkFlow
from airflow.utils.session import provide_session

log = logging.getLogger(__name__)


@provide_session
def add_project(project_name, project_desc, create_by, pool, session=None):
    project = Project(project_name, project_desc, 0, create_by, datetime.now(), pool)
    Project.add_project(project)
    project_user = ProjectUser(project.id, create_by, create_by, datetime.now())
    ProjectUser.add_project_user(project_user)


@provide_session
def delete_project(project_id, session=None):
    # 判断是否有任务
    tasks = Task.query_task(project_id)
    if tasks and len(tasks) > 0:
        return jsonify(code=500, message='项目还存在任务,删除失败!', data=None)
    Project.delete_project(project_id, session)
    ProjectUser.delete_project_user(project_id, None, session)
    ProjectDatasource.delete_project_datasource(project_id, None, session)


@provide_session
def update_project(project_id, project_name, project_desc, project_status, create_by, pool, oa_user_name, session=None):
    old_project = Project.get_project(project_id, session)
    is_admin = user_service.is_admin(oa_user_name)
    if create_by and create_by != old_project.create_by:
        if not is_admin:
            return jsonify(code=500, message='不是管理员，无权限!', data=None)
        project_user = ProjectUser(project_id, create_by, oa_user_name, datetime.now())
        ProjectUser.add_project_user(project_user, session)
    if pool != old_project.pool:
        if not is_admin:
            return jsonify(code=500, message='不是管理员，无权限!', data=None)
        new_project = Project(project_name, project_desc, project_status, create_by, datetime.now(), pool)
        if old_project and old_project.pool != pool:
            # 修改下面的task
            tasks = Task.query_task(project_id)
            for task in tasks:
                task.pool = pool
                Task.update(task, session)
            # 修改下面的pickle
            workflows = WorkFlow.query_workflow(project_id)
            for workflow in workflows:
                dag_pickle = DagPickle.get_by_dag('dag-' + str(workflow.id))
                pickle = copy.deepcopy(dag_pickle.pickle)
                for task in pickle.tasks:
                    task.pool = pool
                    task.queue = pool
                new_dag_pickle = DagPickle(pickle)
                new_dag_pickle.update(session)
        new_project.id = project_id
        Project.update_project(new_project, session)
    else:
        Project.update(project_id, project_name, project_desc, create_by, session)


@provide_session
def get_projects(page, session=None):
    if page == 0:
        projects = Project.get_projects(None, session)
        map_projects = map(Project.to_json, projects)
        return list(map_projects)
    else:
        projects_result = Project.get_projects_page(page, session)
        projects_result.items = list(map(Project.to_json, projects_result.items))
        result = projects_result.to_json()
        return result


@provide_session
def get_project_options(session=None):
    ps = session.query(Project.id, Project.project_name).all()
    rs = [{'id': it[0], 'name': it[1]} for it in ps]
    return rs


@provide_session
def get_project_users(id, page, session=None):
    users_result = User.get_project_users(id, page, session)
    for user in users_result.items:
        oa_user_name = user.oa_user_name
        roles = AuthRole.get_role(None, oa_user_name, session)
        for role in roles:
            rid = role.id
            resources = AuthResource.get_resource(None, rid, session)
            role.resources = resources
        user.roles = roles
    users_result.items = list(map(User.to_json, users_result.items))
    result = users_result.to_json()
    return result


@provide_session
def add_project_users(oa_username, project_id, users, session=None):
    for user in users:
        project_user = ProjectUser(project_id, user, oa_username, datetime.now())
        ProjectUser.add_project_user(project_user, session)


@provide_session
def delete_project_users(project_id, users, session=None):
    for user in users:
        ProjectUser.delete_project_user(project_id, user, session)
